using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace GameOverlayWPF
{
    // 广告数据模型
    public class Advert : ICardItem
    {
        [JsonProperty("id")]
        public string Id { get; set; }
        
        [JsonProperty("title")]
        public string Title { get; set; }
        
        [JsonProperty("author")]
        public string Author { get; set; }
        
        // 头像URL属性 - 确保是完整URL
        private string _avatar;
        [JsonProperty("avatar")]
        public string Avatar 
        { 
            get => _avatar;
            set
            {
                // 如果是相对路径，拼接完整URL
                if (!string.IsNullOrEmpty(value) && !value.StartsWith("http"))
                {
                    _avatar = $"https://maqt.top{(value.StartsWith("/") ? "" : "/")}{value}";
                }
                else
                {
                    _avatar = value;
                }
            }
        }
        
        [JsonProperty("category")]
        public string Category { get; set; }
        
        [JsonProperty("shareTime")]
        public DateTime ShareTime { get; set; }
        
        [JsonProperty("likes")]
        public int Likes { get; set; }
        
        [JsonProperty("views")]
        public int Views { get; set; }
        
        [JsonProperty("description")]
        public string Description { get; set; }
        
        [JsonProperty("link_url")]
        public string LinkUrl { get; set; }
        
        [JsonProperty("price")]
        public decimal Price { get; set; }
        
        [JsonProperty("click_count")]
        public int ClickCount { get; set; }
        
        [JsonProperty("isVip")]
        public bool IsVip { get; set; }
        
        // 图片URL属性 - 确保是完整URL
        private string _imageUrl;
        [JsonProperty("image_url")]
        public string ImageUrl 
        { 
            get => _imageUrl;
            set
            {
                // 如果是相对路径，拼接完整URL
                if (!string.IsNullOrEmpty(value) && !value.StartsWith("http"))
                {
                    _imageUrl = $"https://maqt.top{(value.StartsWith("/") ? "" : "/")}{value}";
                }
                else
                {
                    _imageUrl = value;
                }
            }
        }
        
        // ICardItem 实现
        public string DisplayId => $"ad_{Id}";
        public bool IsAdvertisement => true;
        
        // 用于UI显示的属性映射
        public string UserName => Author;
        public string UserAvatar => Avatar;
        public string WeaponName => Category;
        public int Uses => Views;
        public string SchemeContent => LinkUrl;
    }
    
    public class AdvertListResponse
    {
        public bool Success { get; set; }
        public List<Advert> Data { get; set; }
    }
    
    public class AdvertClickResponse
    {
        public bool Success { get; set; }
        public string Message { get; set; }
    }
    
    public class AdvertService
    {
        private static AdvertService _instance;
        private static readonly HttpClient client = new HttpClient
        {
            Timeout = TimeSpan.FromSeconds(10)
        };
        private static string baseUrl = "https://maqt.top";
        
        // 缓存
        private List<Advert> _cachedAdverts;
        private DateTime _cacheTime;
        private static readonly TimeSpan CacheExpiration = TimeSpan.FromMinutes(5);
        private readonly object _cacheLock = new object();
        
        public static AdvertService Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new AdvertService();
                }
                return _instance;
            }
        }
        
        private AdvertService()
        {
        }
        
        // 获取广告列表
        public async Task<List<Advert>> GetAdvertsAsync()
        {
            lock (_cacheLock)
            {
                if (_cachedAdverts != null && DateTime.Now - _cacheTime < CacheExpiration)
                {
                    System.Diagnostics.Debug.WriteLine("从缓存加载广告数据");
                    return new List<Advert>(_cachedAdverts);
                }
            }
            
            try
            {
                System.Diagnostics.Debug.WriteLine("从API获取广告列表...");
                var response = await client.GetAsync($"{baseUrl}/api/adverts/list");
                var content = await response.Content.ReadAsStringAsync();
                
                if (response.IsSuccessStatusCode)
                {
                    var advertsResponse = JsonConvert.DeserializeObject<AdvertListResponse>(content);
                    if (advertsResponse != null && advertsResponse.Success && advertsResponse.Data != null)
                    {
                        lock (_cacheLock)
                        {
                            _cachedAdverts = advertsResponse.Data;
                            _cacheTime = DateTime.Now;
                        }
                        System.Diagnostics.Debug.WriteLine($"成功获取 {advertsResponse.Data.Count} 个广告");
                        return advertsResponse.Data;
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"获取广告列表失败: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取广告列表异常: {ex.Message}");
            }
            
            return new List<Advert>();
        }
        
        // 记录广告点击
        public async Task<AdvertClickResponse> RecordAdvertClickAsync(string advertId)
        {
            try
            {
                // 处理广告ID格式（支持带'ad_'前缀和不带前缀）
                string cleanAdvertId = advertId;
                if (advertId.StartsWith("ad_"))
                {
                    cleanAdvertId = advertId.Substring(3);
                }
                
                // 验证ID格式
                if (string.IsNullOrEmpty(cleanAdvertId) || !int.TryParse(cleanAdvertId, out _))
                {
                    return new AdvertClickResponse 
                    { 
                        Success = false, 
                        Message = "无效的广告ID格式" 
                    };
                }
                
                var response = await client.PostAsync($"{baseUrl}/api/adverts/{advertId}/click", null);
                var content = await response.Content.ReadAsStringAsync();
                
                if (response.IsSuccessStatusCode)
                {
                    var clickResponse = JsonConvert.DeserializeObject<AdvertClickResponse>(content);
                    return clickResponse ?? new AdvertClickResponse { Success = true, Message = "点击统计成功" };
                }
                else
                {
                    var errorResponse = JsonConvert.DeserializeObject<AdvertClickResponse>(content);
                    return errorResponse ?? new AdvertClickResponse 
                    { 
                        Success = false, 
                        Message = "点击统计失败" 
                    };
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"广告点击统计异常: {ex.Message}");
                return new AdvertClickResponse 
                { 
                    Success = false, 
                    Message = $"点击统计异常: {ex.Message}" 
                };
            }
        }
    }
    
    // 广告插入算法
    public class AdvertInsertionAlgorithm
    {
        // 插入广告到方案列表中
        // VIP广告始终在索引1的位置（第一行第二个）
        public List<object> InsertAdverts(List<Scheme> schemes, List<Advert> allAdverts)
        {
            var result = new List<object>();
            
            // 如果没有方案，直接返回空列表
            if (schemes == null || schemes.Count == 0)
            {
                return result;
            }
            
            // 如果没有广告，直接返回方案列表
            if (allAdverts == null || allAdverts.Count == 0)
            {
                result.AddRange(schemes);
                return result;
            }
            
            // 分离VIP和普通广告
            var vipAdverts = allAdverts.FindAll(ad => ad.IsVip);
            var normalAdverts = allAdverts.FindAll(ad => !ad.IsVip);
            
            System.Diagnostics.Debug.WriteLine($"VIP广告: {vipAdverts.Count} 个, 普通广告: {normalAdverts.Count} 个");
            
            // VIP广告始终在索引1的位置（第一行第二个）
            // 普通广告在其他位置随机插入
            
            int schemeIndex = 0;
            int vipIndex = 0;
            int normalIndex = 0;
            
            // 索引0：第一个方案
            if (schemeIndex < schemes.Count)
            {
                result.Add(schemes[schemeIndex]);
                schemeIndex++;
            }
            
            // 索引1：第一个VIP广告（如果有）
            if (vipIndex < vipAdverts.Count)
            {
                result.Add(vipAdverts[vipIndex]);
                vipIndex++;
                System.Diagnostics.Debug.WriteLine($"VIP广告插入在位置: {result.Count - 1}");
            }
            else if (schemeIndex < schemes.Count)
            {
                // 如果没有VIP广告，继续添加方案
                result.Add(schemes[schemeIndex]);
                schemeIndex++;
            }
            
            // 继续插入剩余的方案，随机插入普通广告
            var random = new Random();
            int nextNormalAdPosition = random.Next(3, 6); // 第一个普通广告在3-5个方案之后
            
            while (schemeIndex < schemes.Count || normalIndex < normalAdverts.Count)
            {
                // 检查是否应该插入普通广告
                if (normalIndex < normalAdverts.Count && result.Count >= nextNormalAdPosition)
                {
                    result.Add(normalAdverts[normalIndex]);
                    normalIndex++;
                    System.Diagnostics.Debug.WriteLine($"普通广告插入在位置: {result.Count - 1}");
                    // 计算下一个普通广告位置
                    nextNormalAdPosition = result.Count + random.Next(3, 6);
                }
                // 插入方案
                else if (schemeIndex < schemes.Count)
                {
                    result.Add(schemes[schemeIndex]);
                    schemeIndex++;
                }
                else
                {
                    break;
                }
            }
            
            // 添加剩余的VIP广告（如果有多个）
            while (vipIndex < vipAdverts.Count)
            {
                result.Add(vipAdverts[vipIndex]);
                vipIndex++;
            }
            
            // 添加剩余的普通广告
            while (normalIndex < normalAdverts.Count)
            {
                result.Add(normalAdverts[normalIndex]);
                normalIndex++;
            }
            
            System.Diagnostics.Debug.WriteLine($"最终列表包含: {result.Count} 个项目 (方案: {schemeIndex}, VIP广告: {vipIndex}, 普通广告: {normalIndex})");
            
            return result;
        }
    }
}
